-module(bmula_sup).
-include("bmula.inc").

-behaviour(supervisor).
-behaviour(application).

%% External exports
-export([upgrade/0]).

%% supervisor callbacks
-export([start/2, stop/1, init/1]).

start(_, _) ->
    webtool:start(),
    supervisor:start_link({local, ?MODULE}, ?MODULE, []).

stop(_) ->
    ok.

%% Add processes if necessary.
upgrade() ->
    {ok, {_, Specs}} = init([]),

    Old = sets:from_list([Name || {Name, _, _, _} <- supervisor:which_children(?MODULE)]),
    New = sets:from_list([Name || {Name, _, _, _, _, _} <- Specs]),
    Kill = sets:subtract(Old, New),

    sets:fold(fun(Id, ok) ->
    	supervisor:terminate_child(?MODULE, Id),
        supervisor:delete_child(?MODULE, Id),
        ok
	end, ok, Kill),

    [supervisor:start_child(?MODULE, Spec) || Spec <- Specs],
    ok.

%% supervisor callback.
init([]) ->
    Random = {bmula_random,
        {bmula_random, start_link, []},
        permanent, 5000, worker, [bmula_random]
    },

    Stats = {bmula_stats,
        {bmula_stats, start_link, []},
        permanent, 5000, worker, [bmula_stats]
    },

    SMTPS_Events = {bmula_smtps_event_manager,
        {gen_event, start_link, [{local, bmula_smtps_event_manager}]},
        permanent, 5000, worker, []
    },

    SMTPS = {bmula_smtps,
        {bmula_smtps, start_link, []},
        permanent, 5000, worker, [bmula_smtps]
    },

    Processes = [Random, Stats, SMTPS_Events, SMTPS],
    {ok, {{one_for_one, 10, 10}, Processes}}.

